package com.projectplace.GUI;

/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import java.util.ArrayList;
import java.util.List;
import com.projectplace.ProjectPlace;
import com.projectplace.R;
import com.projectplace.SingeltonPPClient;
import com.projectplace.GUI.Callback.ViewConversationsCallback;
import com.projectplace.GUI.Callback.CacheCallbackInterface.ResponseMyProjects;
import com.projectplace.GUI.Database.CacheHelper;
import com.projectplace.GUI.adapter.Conversation_myProjects_Adapter;
import com.projectplace.GUI.adapter.Document_Document_Adapter;
import com.projectplace.api.DocumentsApi;
import com.projectplace.api.OAUTH;
import com.projectplace.api.UserApi;
import com.projectplace.api.objectResponses.Project;
import com.projectplace.api.objectResponses.DocumentsApi.Documents;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;

public class DocumentsActivity extends Activity {
	
	/*
	 * This class is exactly the same as Conversation except that we want to start a different intent onListItemClick!
	 */
	
	private final String LOG_TAG ="Documents";
	private final String identifier="projectID";
	private static ViewFlipper mFlipper;

	private static ArrayList<Project> project;
	private static Conversation_myProjects_Adapter projectAdapter;
	private Activity activity;
	private List<Documents> documents;
	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private GestureDetector gestureDetector;
	View.OnTouchListener gestureListener;
	private boolean firstView;
	private static Handler hand;
	private ListView firstList;
	private ListView secList;
	
	public void onCreate(Bundle savedInstanceState){
		Log.d(LOG_TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.documentflipper);
		firstView = true;
		mFlipper = (ViewFlipper) findViewById(R.id.ViewFlipperDocument);
		project = new ArrayList<Project>();
		activity = this;
		firstList = (ListView) findViewById(R.id.document_first);
		secList = (ListView) findViewById(R.id.document_second);
		hand = new Handler();
		
		CacheHelper.getMyProjects(activity, hand, new ResponseMyProjects() {
			public void onFail(Error err) {
				Log.d(LOG_TAG, err.getMessage());		
			}
			//Previous data could still be here so we clear the list and add everything from the cache
			public void onReceive(List<Project> cachedProjects) {
				project.clear();
				project.addAll(cachedProjects);
				projectAdapter = new Conversation_myProjects_Adapter(activity,project);
				firstList.setAdapter(projectAdapter);
			}
		}); 
		
		gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
        firstList.setOnTouchListener(gestureListener);
        secList.setOnTouchListener(gestureListener);
        firstList.setOnItemClickListener(new OnItemClickListener() {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long id) {
		
			String idOfClickedProject = String.valueOf(id);
			Log.d(LOG_TAG, idOfClickedProject);
			Intent intent = new Intent().setClass(activity, DocumentsContainerContent.class);
			intent.putExtra(identifier, idOfClickedProject);
			startActivity(intent);
		}
	});

	}
	
	private void documentClicked(String id,int position){
		if(id != null){
			Intent intent = new Intent().setClass(this, DocumentsView.class);
			intent.putExtra("size",documents.get(position).getSize());
			intent.putExtra("type",documents.get(position).getType());
			intent.putExtra("name",documents.get(position).getName());
			intent.putExtra("time", documents.get(position).getModified_time());
			intent.putExtra("version", documents.get(position).getVersion());
			intent.putExtra("id", id);
			startActivity(intent);
		}
		else
			Toast.makeText(activity, "Something went very wrong please try again", Toast.LENGTH_LONG).show();
	}
	
	public void onResume(){
		super.onResume();
		SharedPreferences mSettings = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE);
		
		if(mSettings.contains(OAUTH.USER_TOKEN) && mSettings.contains(OAUTH.USER_SECRET)) {
			UserApi.getUserProjects(SingeltonPPClient.getInstance(), hand, new com.projectplace.api.Callback.Callback.ResponseListenerUserProjects() {
				public void SERVER_ERROR(Error err) {
					Log.d(LOG_TAG, "SERVER_ERROR");
				} 
				
				public void BAD_TOKEN_ERROR(Error err) {  
					SharedPreferences.Editor editor = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE).edit();
					
					//Clear the saved token and secret since they are deprecated if we end up here
					editor.remove(OAUTH.USER_TOKEN);
					Log.d(LOG_TAG, "Clearing OAuth Token");
					editor.remove(OAUTH.USER_SECRET);
					Log.d(LOG_TAG, "Clearing OAuth Secret");
					editor.commit();				
					Log.d(LOG_TAG, "Innan getUsrProjects");
					ProjectPlace ac;
					ac = (ProjectPlace)activity.getParent();
					ac.initiateOAUTH(); 
					Log.d(LOG_TAG, "de finns inte");
				}   
	
				public void onReceive(List<Project> userProjects) {
					Log.d(LOG_TAG, "I DO GET ANSWER!!"); 				
					if(project != null){
						//Not perfect! works as long as the user isn't part of many(above 10) projects since is freezes the ui thread
						for(Project p:userProjects){
							if(!project.contains(p))
								project.add(p);
						}
						if(projectAdapter == null){
							projectAdapter = new Conversation_myProjects_Adapter(activity,project);
							firstList.setAdapter(projectAdapter);
						}else{
							projectAdapter.notifyDataSetChanged();
						} 
						
					}
				} 
			});
			
			DocumentsApi.getUserRecentDocuments(SingeltonPPClient.getInstance(), hand, new com.projectplace.api.Callback.Callback.ResponseListenerUserRecentDocuments() {
					
					public void SERVER_ERROR(Error err) {
						// TODO Auto-generated method stub
						 
					}
					
					public void BAD_TOKEN_ERROR(Error err) {
						// TODO Auto-generated method stub
						
					}
	
					public void onReceive(List<Documents> documentRecent) {
						documents = documentRecent;
						secList.setAdapter(new Document_Document_Adapter(activity, documents, new ViewConversationsCallback() {
							
							public void onViewClick(String id,String name, int position) {
								// TODO Auto-generated method stub
								documentClicked(id,position);
							}
						}));
						
					}
				});
		}
	}
	
	/*@Override
	public void onListItemClick(ListView l,View v,int position,long id){
		String idOfClickedProject = String.valueOf(id);
		Log.d(LOG_TAG, idOfClickedProject);
		Intent intent = new Intent().setClass(this, DocumentsContainerContent.class);
		intent.putExtra(identifier, idOfClickedProject);
		startActivity(intent);
	}*/
	
	 class MyGestureDetector extends SimpleOnGestureListener {
	        @Override
	        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	        	
	            try {
	                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
	                    return false;
	                if(firstView == true){
	                // left to right swipe
	                  if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	                	  Log.d(LOG_TAG, "SWIPING left to right!!!");
	                	  firstView = false;
	                	  mFlipper.setInAnimation(inFromRightAnimation());
	                	  mFlipper.setOutAnimation(outToLeftAnimation());
	                	  mFlipper.showNext();
	                	  
	                	  
	                }
	                  }else{
	                  // right to left swipe
	                  if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	                	  Log.d(LOG_TAG, "SWIPING right to left!!!");
	                	  firstView = true;
	                	  mFlipper.setInAnimation(inFromLeftAnimation());
	                	  mFlipper.setOutAnimation(outToRightAnimation());
	                	  mFlipper.showPrevious();
	                	  
	                }
	                  }
	            } catch (Exception e) {
	                // nothing
	            }
	            return false;
	        }
	        
	        public boolean onTouchEvent(MotionEvent event) {
	            if (gestureDetector.onTouchEvent(event))
	    	        return true;
	    	    else
	    	    	return false;
	        }
	    }
	 
	 
	 
	 protected Animation inFromRightAnimation() {
         Animation inFromRight = new TranslateAnimation(
                         Animation.RELATIVE_TO_PARENT, +1.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f);
         inFromRight.setDuration(300);
         inFromRight.setInterpolator(new AccelerateInterpolator());
         return inFromRight;
 }

 protected Animation outToLeftAnimation() {
         Animation outtoLeft = new TranslateAnimation(
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, -1.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f);
         outtoLeft.setDuration(300);
         outtoLeft.setInterpolator(new AccelerateInterpolator());
         return outtoLeft;
 }

 protected Animation inFromLeftAnimation() {
         Animation inFromLeft = new TranslateAnimation(
                         Animation.RELATIVE_TO_PARENT, -1.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f);
         inFromLeft.setDuration(300);
         inFromLeft.setInterpolator(new AccelerateInterpolator());
         return inFromLeft;
 }

 protected Animation outToRightAnimation() {
         Animation outtoRight = new TranslateAnimation(
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, +1.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f,
                         Animation.RELATIVE_TO_PARENT, 0.0f);
         outtoRight.setDuration(300);
         outtoRight.setInterpolator(new AccelerateInterpolator());
         return outtoRight;
 }
	
}
